# -*- coding:utf-8 -*-
#ihome所使用的所有模型

from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from . import db
import json

class BaseModel(object):
    """模型基类，为每个模型补充创建时间与更新时间"""

    create_time = db.Column(db.DateTime, default=datetime.now)  # 记录的创建时间
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)  # 记录的更新时间

class Shop(BaseModel,db.Model):
    """店铺"""
    __tablename__="cou_shops"

    id=db.Column(db.Integer,primary_key=True)
    shop_id=db.Column(db.String(32))
    name=db.Column(db.String(32))
    area_id = db.Column(db.Integer, db.ForeignKey("cou_area_info.id"), nullable=False)  # 归属地的区域编号
    foods=db.relationship('Food',backref='shop')
    discounts=db.relationship('Manjian',backref='shop')
    juans=db.relationship('Juan',backref='shop')
    taocan=db.relationship('Taocan',backref='shop')
class Food(BaseModel,db.Model):
    """商品食物"""
    __tablename__='cou_foods'

    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(32))
    price=db.Column(db.Integer)
    shop_id=db.Column(db.Integer,db.ForeignKey('cou_shops.id'),nullable=False)
    taocan_id=db.Column(db.Integer,db.ForeignKey('cou_taocan.id'))
    url = db.Column(db.String(256))  # 图片的路径
class Juan(BaseModel, db.Model):
    """优惠卷"""
    __tablename__='cou_juan'

    id=db.Column(db.Integer,primary_key=True)
    man=db.Column(db.Integer)
    jian=db.Column(db.Integer)
    is_huiyuanjuan= db.Column(db.Boolean,nullable=False)
    huiyuan_price=db.Column(db.Integer)
    shop_id=db.Column(db.Integer,db.ForeignKey('cou_shops.id'),nullable=False)
    taocan=db.relationship('Taocan',backref='juan')
class Manjian(BaseModel,db.Model):
    """满减"""
    __tablename__='cou_manjian'

    id=db.Column(db.Integer,primary_key=True)
    shop_id=db.Column(db.Integer,db.ForeignKey('cou_shops.id'),nullable=False)
    man=db.Column(db.Integer)
    jian=db.Column(db.Integer)
    taocan=db.relationship('Taocan',backref='manjian')
class Area(BaseModel, db.Model):
    """城区"""

    __tablename__ = "cou_area_info"

    id = db.Column(db.Integer, primary_key=True)  # 区域编号
    name = db.Column(db.String(32), nullable=False)  # 区域名字
    shops = db.relationship("Shop", backref="area")  # 区域的店铺
    taocans = db.relationship("Taocan", backref="area")  # 区域的套餐
    def to_dict(self):
        """将对象转换为字典数据"""
        area_dict = {
            "aid": self.id,
            "aname": self.name
        }
        return area_dict
# 套餐食物表，建立套餐与食物的多对多关系
taocan_foods = db.Table(
    "cou_taocan_foods",
    db.Column("food_id", db.Integer, db.ForeignKey("cou_foods.id"), primary_key=True),  # 食物编号
    db.Column("taocan_id", db.Integer, db.ForeignKey("cou_taocan.id"), primary_key=True)  # 套餐编号
)
class Taocan(BaseModel,db.Model):
    """套餐"""
    __tablename__="cou_taocan"

    id=db.Column(db.Integer,primary_key=True)
    area_id=db.Column(db.Integer, db.ForeignKey("cou_area_info.id"), nullable=True)  # 归属地的区域编号
    name= db.Column(db.String(32))
    discount=db.Column(db.Integer)
    price=db.Column(db.Integer)
    check_time=db.Column(db.Integer,default=0)
    foods=db.relationship('Food',backref='taocan', secondary=taocan_foods)
    foods_info=db.Column(db.String(256))
    shop_id=db.Column(db.Integer,db.ForeignKey('cou_shops.id'),nullable=False)
    juan_id=db.Column(db.Integer,db.ForeignKey('cou_juan.id'),nullable=True)
    manjian_id=db.Column(db.Integer,db.ForeignKey('cou_manjian.id'),nullable=True)
    
    def to_index(self):
        taocan_dict={
            'id':self.id,
            'img_url':self.foods[0].url,
            'name':self.name
        }
        return taocan_dict
    def to_detail(self):

        taocan_dict={
            'id':self.id,
            'shop_name':self.shop.name,
            'price':self.price/100,
            'title':self.name,
            'food':[
                {'img_url':i.url,
                'num':json.loads(self.foods_info)[str(i.id)],
                'price':(i.price)/100,#json.loads(self.foods_info)[str(i.id)]['price'],
                'name':i.name,#json.loads(self.foods_info)[str(i.id)]['name'],
                } 
            for i in self.foods],
            'juan':{'man':self.juan.man/100,'jian':self.juan.jian/100} if self.juan else 0,
            'manjian':{'man':self.manjian.man/100,'jian':self.manjian.jian/100} if self.manjian else 0
        }
        total_price=0
        for i in taocan_dict['food']:
            total_price+=i['price']*i['num']
        total_jian=0
        total_jian=(total_jian+taocan_dict['juan']['jian']) if taocan_dict['juan'] else total_jian
        total_jian=(total_jian+taocan_dict['manjian']['jian']) if taocan_dict['manjian'] else total_jian
        taocan_dict['total_price']=total_price
        taocan_dict['total_jian']=total_jian
        return taocan_dict
   
        



